package com.onion.auth.support.provider;

import com.onion.auth.config.OnionAuthConfig;
import com.onion.auth.support.AuthorizeProvider;
import com.onion.auth.support.vo.AuthUser;
import com.onion.cache.OnionCache;
import com.onion.cache.support.enums.CacheType;

public class CacheAuthProvider implements AuthorizeProvider<String> {

    @Override
    public String getType() {
        return "onion.authc.cache";
    }

    @Override
    public AuthUser<String> getAuthUser(String userToken) {
        return (AuthUser)OnionCache.getObject(this.buildAuthTokenKey(userToken));
    }

    @Override
    public void cacheToken(String userToken, AuthUser<String> authUser) {
        OnionCache.setObjectEx(this.buildAuthTokenKey(userToken), authUser, OnionAuthConfig.getTokenTimeout());
    }

    @Override
    public void refreshToken(String userToken) {
        String userTokenKey = this.buildAuthTokenKey(userToken);
        if(OnionCache.exist(userTokenKey, CacheType.OBJECT)){
            OnionCache.expire(userTokenKey, CacheType.OBJECT, OnionAuthConfig.getTokenTimeout());
        }
    }

    @Override
    public void clearToken(String userToken) {
        String userTokenKey = this.buildAuthTokenKey(userToken);
        OnionCache.delete(userTokenKey);
    }

    @Override
    public boolean hasRole(String userId, String role) {
        return false;
    }

    @Override
    public boolean hasPermission(String userId, String permission) {
        return false;
    }

    /**
     * 构建用户权限Token
     * @param userToken
     * @return
     */
    private String buildAuthTokenKey(String userToken){
        return OnionAuthConfig.AUTH_TOKEN_PREFIX + userToken;
    }

}